package com.yuanduo_app.widget.record;

import android.view.SurfaceView;

import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.xujl.fastlib.utils.AppManager;
import com.xujl.task.RxExecutor;
import com.xujl.task.RxHelper;

import com.yuanduo_app.MainActivityControl;
import com.yuanduo_app.MainApplication;
import com.yuanduo_app.bridge.DataModule;
import com.yuanduo_app.consts.FileConst;
import com.yuanduo_app.consts.PermissionGroup;
import com.yuanduo_app.consts.RNEvent;
import com.yuanduo_app.event.PermissionsEvent;
import com.yuanduo_app.manager.RNModuleManager;
import com.yuanduo_app.manager.RecorderManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 录像控件
 */
public class RecordRnView extends SimpleViewManager<SurfaceView> {
    private static final int START_CAMERA = 1;
    private static final int TAKE_VIDEO = 2;
    private static final int STOP_TAKE_VIDEO = 3;
    private static final int CLOSE_CAMERA = 4;
    private RecorderManager mRecorderManager;
    private RecordVideoUtil mRecordVideoUtil;

    @NonNull
    @Override
    public String getName () {
        return "RecordRnView";
    }

    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap () {
        Map<String, Integer> map = new HashMap<>();
        map.put("startCamera", START_CAMERA);
        map.put("takeVideo", TAKE_VIDEO);
        map.put("stopTakeVideo", STOP_TAKE_VIDEO);
        map.put("closeCamera", CLOSE_CAMERA);
        return map;
    }

    @NonNull
    @Override
    protected SurfaceView createViewInstance (@NonNull ThemedReactContext reactContext) {
        final SurfaceView previewView = new SurfaceView(reactContext);
        mRecordVideoUtil = new RecordVideoUtil(AppManager.getAppManager().findActivity(MainActivityControl.class), previewView);
        return previewView;
    }


    @Override
    public void receiveCommand (@NonNull SurfaceView previewView, int commandId, @Nullable ReadableArray args) {
        super.receiveCommand(previewView, commandId, args);
        switch (commandId) {
            case START_CAMERA:
                try {
                    EventBus.getDefault().register(this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                startPreview();
                break;
            case TAKE_VIDEO:
                startPreview();
                mRecordVideoUtil.startRecord(FileConst.RECORD + FileConst.RECORD_CACHE);
                break;
            case STOP_TAKE_VIDEO:
                mRecordVideoUtil.stopRecord();
                RxExecutor.getInstance()
                        .executeTask(new RxHelper.DelayTask(1000) {
                            @Override
                            public void timeOver () {
                                DataModule module = RNModuleManager.getInstance().getModule(DataModule.class);
                                if (module != null) {
                                    module.sendEvent(RNEvent.RECORD_FILE_RESULT, FileConst.RECORD + FileConst.RECORD_CACHE);
                                }
                            }
                        });
                break;
            case CLOSE_CAMERA:
                EventBus.getDefault().unregister(this);
                mRecordVideoUtil.stopPreview();
                break;
            default:
                break;
        }
    }

    private void startPreview () {
        if (!EasyPermissions.hasPermissions(MainApplication.getApplication(), PermissionGroup.RECORD)) {
            //没有授权时发起授权
            AppManager.getAppManager().findActivity(MainActivityControl.class).requestRuntimePermissions(PermissionGroup.RECORD);
            return;
        }
        mRecordVideoUtil.startPreview();
    }

    @Subscribe
    public void onPermissionsEvent (PermissionsEvent event) {
        if (event.isSuccess() && EasyPermissions.hasPermissions(MainApplication.getApplication(), PermissionGroup.RECORD)) {
            startPreview();
        } else {
            DataModule module = RNModuleManager.getInstance().getModule(DataModule.class);
            if (module != null) {
                module.sendEvent(RNEvent.PAGE_CONTROL, RNEvent.PAGE_CONTROL_EXIT);
            }
        }
    }
//    @NonNull
//    @Override
//    protected CameraXCustomPreviewView createViewInstance (@NonNull ThemedReactContext reactContext) {
//        final CameraXCustomPreviewView previewView = new CameraXCustomPreviewView(reactContext);
//        mRecorderManager = new RecorderManager();
//        mRecorderManager.bindView(previewView);
//        mRecorderManager.startCamera(AppManager.getAppManager().findActivity(MainActivityControl.class));
//        return previewView;
//    }
//
//
//
//    @Override
//    public void receiveCommand (@NonNull CameraXCustomPreviewView previewView, int commandId, @Nullable ReadableArray args) {
//        super.receiveCommand(previewView, commandId, args);
//        switch (commandId) {
//            case START_CAMERA:
//
//                mRecorderManager.startCamera(AppManager.getAppManager().findActivity(MainActivityControl.class));
//                break;
//            case TAKE_VIDEO:
//                mRecorderManager.takeVideo(new VideoCapture.OnVideoSavedCallback() {
//                    @Override
//                    public void onVideoSaved (@NonNull File file) {
//                        DataModule module = RNModuleManager.getInstance().getModule(DataModule.class);
//                        if (module != null) {
//                            module.sendEvent(RNEvent.RECORD_FILE_RESULT, file.getAbsolutePath());
//                        }
//                    }
//
//                    @Override
//                    public void onError (int videoCaptureError, @NonNull String message, @Nullable Throwable cause) {
//                        ToastUtils.toast("视频保存失败！");
//                    }
//                });
//                break;
//            case STOP_TAKE_VIDEO:
//                mRecorderManager.stopTakeVideo();
//                break;
//            default:
//                break;
//        }
//    }
}
